﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReceiptTracker
{
    public partial class FormAddReceipt : Form
    {
        private List<Shop> shopList = new List<Shop>();
        private SQLiteDB db;
        public FormAddReceipt(SQLiteDB db)
        {
            InitializeComponent();     
            this.db = db;
            datePicker.MaxDate = DateTime.Today;
            //Initialize shop list
            this.shopList.Clear();
            db.SQLQuery("SELECT * FROM Shops;");
            foreach (DataRow row in db.QueryResult.Rows)
            {
                shopList.Add(new Shop(Convert.ToInt32(row["id"]), row["name"].ToString(), Convert.ToInt32(row["category"])));
            }
            comboBoxShop.DataSource = shopList;
            comboBoxShop.ValueMember = "name";
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            Regex rgx = new Regex(@"^[0-9]*\.?[0-9]*$");
            if (comboBoxShop.SelectedIndex == -1)
            {
                MessageBox.Show("Can't add a receipt without a shop", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if(textBoxSpent.Text == "")
            {
                MessageBox.Show("Please enter a value for how much was spent", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (!rgx.IsMatch(textBoxSpent.Text))
            {
                MessageBox.Show("Entered value for amount spent is not valid\nPlease enter on the format 123.45", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                db.SQLCommand("INSERT INTO Receipts (date, spent, shop) VALUES ('" + datePicker.Value.Date.ToShortDateString() + "', " +
                    textBoxSpent.Text + ", " + shopList[comboBoxShop.SelectedIndex].Id + ");");
                this.DialogResult = DialogResult.OK; 
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
